<?php
/**
 * @author quyang <quyang@>
 * @version 
 */

$DBConf['master'] = array(
	'host'	=>	'192.168.224.58',
	'user'	=>	'user',
	'pass'	=>	'123qwe',
	'db'	=>	'unicom_auction',
);
$DBConf['slaver'] = array(
	'host'	=>	'192.168.224.76',
	'user'	=>	'auction',
	'pass'	=>	'123qwe',
	'db'	=>	'unicom_auction',
);


Class SimpleDB {
	private $dbconf;
	private $mode;
	private static $dbo;
	private static $dblink;

	public function __construct($mode, $DBConf){
		if('s' === $mode){
			$this->dbconf = $DBConf['slaver'];
		} else {
			$mode = 'm';
			$this->dbconf = $DBConf['master'];
		}
		$this->mode = $mode;
		if(!$this->_initDB()){
			return false;
		}
	}

	public static function getSingleton($mode = 's'){
		if (!isset(self::$dbo[$mode]) || !is_object(self::$dbo[$mode]) || !mysql_ping(self::$dblink[$mode])){
			self::$dbo[$mode] = new self($mode);
		}
		return self::$dbo[$mode];
	}
	
	private function _initDB(){
		self::$dblink[$this->mode] = mysql_connect($this->dbconf['host'],$this->dbconf['user'],$this->dbconf['pass']);
		if(!mysql_select_db($this->dbconf['db'])){
			//TODO need a log?
			return false;
		}
		return is_resource(self::$dblink[$this->mode]);
	}
	public function setNames($names = 'utf8'){
		mysql_query("SET NAMES '{$names}'", self::$dblink[$this->mode]); 
        mysql_query("SET CHARACTER_SET_CLIENT='{$names}'", self::$dblink[$this->mode]); 
        mysql_query("SET CHARACTER_SET_RESULTS='{$names}'", self::$dblink[$this->mode]); 
	}

	public function query($sql){
		return $this->query_result = mysql_query($sql,self::$dblink[$this->mode]);
	}

	public function escape_string($value) {
		return mysql_escape_string($value);
	}
	
	public function fetchAll(){
		$stuff = NULL;
		if (!empty($this->query_result)) {
			while ($tmp = mysql_fetch_assoc($this->query_result)) {
				$stuff[] = $tmp;
			}
		}
		return $stuff;
	}
	public function closeDB(){
		return mysql_close(self::$dblink[$this->mode]);
	}
	
}

?>
